package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserServices;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * date: 2024/09/19 16:30<br/>
 * Description:站内信
 *
 * @author: jmy <br/>
 */

@Slf4j
@RestController
@RequestMapping("/message")
@Api(tags = "站内信接口")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserServices userServices;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @NotNull @RequestParam("content") @ApiParam("消息内容") String content,
                          @NotNull @RequestParam("receiveUserId") @ApiParam("接收人id") Long receiveUserId) {

        //1.参数校验
        if (content == null || "".equals(content.trim()) || receiveUserId == null) {

            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.fillInStackTrace().toString());
            throw e;
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //2.获取发送人信息 并校验发送人状态
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        System.out.println(user);
        if (user.getState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
            log.error(e.fillInStackTrace().toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if (user.getDeleteState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
            log.error(e.fillInStackTrace().toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //3.校验接收者用户是否存在 以及状态
        User receiveUser = userServices.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.fillInStackTrace().toString());
            return AppResult.failed(ResultCode.FAILED);
        }

        //4.校验接收人是否是本人
        if (user.getId() == receiveUserId) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_RECEIVER_ERROR));
            log.error(e.fillInStackTrace().toString());
            return AppResult.failed(ResultCode.FAILED_MESSAGE_RECEIVER_ERROR);
        }

        //5.封装成message
        Message message = new Message();
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        message.setPostUserId(user.getId());

        //6.调用services
        messageService.create(message);
        return AppResult.success("发送成功");
    }

    @ApiOperation("获取用户未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //1.获取用户信息
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);

        //2.查询未读信息数
        Integer result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);
    }


    /**
     * date: 2024/09/20 10:41<br/>
     * Description:
     * 查询用户所有站内信
     *
     * @author: jmy <br/>
     */
    @ApiOperation("获取用户站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        //1.获取用户信息
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);

        //2.查询未读信息数
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(result);
    }


    /**
     * date: 2024/09/20 11:37<br/>
     * Description: 更新 站内消息状态
     *
     * @param id    站内信id
     * @param state 目标状态
     * @author: jmy <br/>
     */
    @ApiOperation("更新站内信状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @NotNull @RequestParam("id") Long id,
                              @ApiParam("目标状态") @NotNull @RequestParam("state") Byte state) {

        //1.参数校验
        if (id < 0 || state < 0 || state > 2) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //2.查询 该站内信，判断是否存在
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //3.校验站内信 是不是发送给自己的
        User receiveUser = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (receiveUser.getId() != message.getReceiveUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //调用services
        Integer result = messageService.updateStateById(id, state);

        //3.返回结果
        if (result == 0) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.success(result);
    }

    /**
     * date: 2024/09/20 16:59<br/>
     * Description: 回复站内信接口
     *
     * @author: jmy <br/>
     */
    @ApiOperation("回复站内信内容")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("站内信id") @NotNull @RequestParam("repliedId") Long repliedId,
                           @ApiParam("回复内容") @NotNull @RequestParam("content") String content) {

        //1.参数校验
        if (repliedId < 0 || content == null) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取被回复消息的详情 校验其状态
        Message existMessage = messageService.selectById(repliedId);
        if (existMessage.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //获取回复人信息（登录用户） 校验其状态
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED);
        }
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能给自己回复
        if (user.getId() == existMessage.getPostUserId()) {
            return AppResult.failed("不能给自己回复站内信");
        }
        //构造回复 message
        Message replyMessage = new Message();
        replyMessage.setPostUserId(user.getId());
        replyMessage.setReceiveUserId(existMessage.getPostUserId());
        replyMessage.setContent(content);
        replyMessage.setCreateTime(new Date());
        replyMessage.setUpdateTime(new Date());

        //调用services
        messageService.reply(repliedId, replyMessage);
        return AppResult.success("回复成功");
    }

}
